package logic

import (
	"context"
	"encoding/json"
	"time"
	"user/models/cache"
	"user/models/mysql"

	"user/userrpc/internal/svc"
	"user/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *userrpc.ListRequest) (*userrpc.ListResponse, error) {
	// todo: add your logic here and delete this line

	var users []mysql.User
	cacheData, _ := cache.Rdb.Get(cache.Ctx, "listUsers").Result()
	if cacheData == "" {
		mysql.DB.Find(&users)
		jsonData, _ := json.Marshal(users)
		cache.Rdb.Set(cache.Ctx, "listUsers", jsonData, time.Hour)
	}

	var listUsers []*userrpc.ListUser
	for _, user := range users {
		list := userrpc.ListUser{
			Account: user.Account,
			Id:      int64(user.ID),
		}
		listUsers = append(listUsers, &list)
	}

	return &userrpc.ListResponse{
		List: listUsers,
	}, nil
}
